package com.example.demo.pdfutils;


import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
import com.itextpdf.text.pdf.draw.LineSeparator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class OrderPdfReport {

    // main测试
    public static void main(String[] args) throws Exception {
        try {
            // 1.新建document对象
            Document document = new Document(PageSize.A4);

            // 2.建立一个书写器(Writer)与document对象关联
            File file = new File("D:\\orderPDF.pdf");
            file.createNewFile();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            // 水印
            writer.setPageEvent(new Watermark("Filez"));
            // 页眉/页脚
//            writer.setPageEvent(new MyHeaderFooter());

            // 3.打开文档
            document.open();
            // 标题
            document.addTitle("Title@PDF-Java");
            // 作者
            document.addAuthor("Author@umiz");
            // 主题
            document.addSubject("Subject@iText pdf sample");
            // 关键字
            document.addKeywords("Keywords@iTextpdf");
            // 创建者
            document.addCreator("Creator@umiz`s");

            // 4.向文档中添加内容
            new OrderPdfReport().generatePDF(document);

            // 5.关闭文档
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 定义全局的字体静态变量
    private static Font titlefont;
    private static Font headfont;
    private static Font keyfont;
    private static Font textfont;
    // 最大宽度
    private static int maxWidth = 520;
    // 静态代码块
    static {
        try {
            // 不同字体（这里定义为同一种字体：包含不同字号、不同style）
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            titlefont = new Font(bfChinese, 16, Font.BOLD);
            headfont = new Font(bfChinese, 12, Font.BOLD);
            keyfont = new Font(bfChinese, 10, Font.BOLD);
            keyfont.setColor(BaseColor.RED);
            textfont = new Font(bfChinese, 9, Font.NORMAL);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成PDF文件
     * Chunk:块对象,可配置字符间距、字符+背景色、背景色的矩形大小可任意调整
     *
     * Phrase:短语可配置行间距、不会另起一行
     */

    public void generatePDF(Document document) throws Exception {
        // 段落
        Paragraph paragraph = new Paragraph("Filez", titlefont);
        //行间距
        paragraph.setLeading(20f);
        //设置段落上空白
        paragraph.setSpacingBefore(5f);
        //设置段落下空白
        paragraph.setSpacingAfter(10f);

        // 直线
        Paragraph p1 = new Paragraph();
        LineSeparator lineSeparator = new LineSeparator();
        lineSeparator.setLineColor(BaseColor.LIGHT_GRAY);
        lineSeparator.setLineWidth(0.5f);
        p1.add(new Chunk(lineSeparator));

        Paragraph p2 = new Paragraph("Lenovo Cloud 团队版套餐",textfont);
        //设置段落下空白
        p2.setSpacingBefore(10f);
        Paragraph p3 = new Paragraph("One Park Place,Floor 6",textfont);
        Paragraph p4 = new Paragraph("NewYark Street Upeer 23 number",textfont);

        Paragraph p5 = new Paragraph("迪拜 2",textfont);
        Paragraph emailPara = new Paragraph("xxxx@lenovocloud.com",textfont);
        emailPara.setSpacingAfter(10f);



        Paragraph p6 = new Paragraph("李鸿章的账单",headfont);
        p6.setSpacingAfter(5f);

        // 表格
        PdfPTable table1 = createTable(new float[] { 120, 120, 120 });

        table1.addCell(createCell("至", keyfont, Element.ALIGN_LEFT,BaseColor.LIGHT_GRAY));
        table1.addCell(createCell("日期", keyfont, Element.ALIGN_LEFT,BaseColor.LIGHT_GRAY));
        table1.addCell(createCell("账单ID", keyfont, Element.ALIGN_LEFT,BaseColor.LIGHT_GRAY));

        Integer totalQuantity = 0;
        for (int i = 0; i < 3; i++) {
            table1.addCell(createCell("起床", textfont,Element.ALIGN_LEFT));
            table1.addCell(createCell("吃午饭", textfont,Element.ALIGN_LEFT));
            table1.addCell(createCell("午休", textfont,Element.ALIGN_LEFT));
            totalQuantity ++;
        }

        // 表格
        PdfPTable table2 = createTable(new float[] { 120, 120 });
        table2.setSpacingBefore(20f);
        table2.setSpacingAfter(20f);
        table2.addCell(createCell("Product", keyfont, Element.ALIGN_LEFT,BaseColor.LIGHT_GRAY));
        table2.addCell(createCell("Price", keyfont, Element.ALIGN_LEFT,BaseColor.LIGHT_GRAY));

        for (int i = 0; i < 2; i++) {
            table2.addCell(createCell("起床", textfont,Element.ALIGN_LEFT));
            table2.addCell(createCell("吃午饭", textfont,Element.ALIGN_LEFT));
        }

        table2.addCell(createTotalCell("Total:", keyfont));
        table2.addCell(createTotalCell("US$750.00", keyfont));




        Chunk chunk = new Chunk("service content",keyfont);


        // 最下面表格
        PdfPTable table3 = createTable(new float[] { 20,120 });
        table3.setSpacingBefore(5f);
        for (int i = 0; i < 8; i++) {
            table3.addCell(createImageCell());
            table3.addCell(createCell(i+"TB secure stroge", textfont,Element.ALIGN_LEFT));
        }


        document.add(paragraph);
        document.add(p1);
        document.add(p2);
        document.add(p3);
        document.add(p4);
        document.add(p5);
        document.add(emailPara);
        document.add(p6);
        document.add(table1);
        document.add(table2);
        document.add(chunk);
        document.add(table3);


    }


/**------------------------创建表格单元格的方法start----------------------------*/
    /**
     * 创建单元格(指定字体)
     * @param value
     * @param font
     * @return
     */
    public PdfPCell createCell(String value, Font font) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setPhrase(new Phrase(value, font));
        cell.setBorder(0);
        return cell;
    }

    public PdfPCell createTotalCell(String value, Font font) {
        PdfPCell cell = new PdfPCell();
        cell.setFixedHeight(40f);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setPhrase(new Phrase(value, font));
        cell.setBorder(0);
        return cell;
    }

    /**
     * 创建单元格（指定字体、水平..）
     * @param value
     * @param font
     * @param align
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align,BaseColor baseColor) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setBorder(0);
        cell.setBackgroundColor(baseColor);
        return cell;
    }


    public PdfPCell createCell(String value, Font font, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setBorder(0);
        return cell;
    }

    public PdfPCell createImageCell() throws IOException, BadElementException {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setBorder(0);
        Image image = Image.getInstance("D:\\1.jpg");
//        Image image = Image.getInstance("https://img-blog.csdn.net/20180801174617455?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zNzg0ODcxMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70");
        image.setAlignment(Image.ALIGN_CENTER);
        image.setBorder(Image.BOX);
        image.scaleToFit(10, 10);

        cell.addElement(image);

        return cell;
    }

    /**
     * 创建单元格（指定字体、水平居..、单元格跨x列合并）
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, int colspan) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }
    /**
     * 创建单元格（指定字体、水平居..、单元格跨x列合并、设置单元格内边距）
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @param boderFlag
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        cell.setPadding(3.0f);
        if (!boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(15.0f);
            cell.setPaddingBottom(8.0f);
        } else if (boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(0.0f);
            cell.setPaddingBottom(15.0f);
        }
        return cell;
    }
    /**
     * 创建单元格（指定字体、水平..、边框宽度：0表示无边框、内边距）
     * @param value
     * @param font
     * @param align
     * @param borderWidth
     * @param paddingSize
     * @param flag
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setBorderWidthLeft(borderWidth[0]);
        cell.setBorderWidthRight(borderWidth[1]);
        cell.setBorderWidthTop(borderWidth[2]);
        cell.setBorderWidthBottom(borderWidth[3]);
        cell.setPaddingTop(paddingSize[0]);
        cell.setPaddingBottom(paddingSize[1]);
        if (flag) {
            cell.setColspan(2);
        }
        return cell;
    }
/**------------------------创建表格单元格的方法end----------------------------*/


/**--------------------------创建表格的方法start------------------- ---------*/
    /**
     * 创建默认列宽，指定列数、水平(居中、右、左)的表格
     * @param colNumber
     * @param align
     * @return
     */
    public PdfPTable createTable(int colNumber, int align) {
        PdfPTable table = new PdfPTable(colNumber);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(align);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }
    /**
     * 创建指定列宽、列数的表格
     * @param widths
     * @return
     */
    public PdfPTable createTable(float[] widths) {
        PdfPTable table = new PdfPTable(widths);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
            table.setSpacingBefore(5f);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }
    /**
     * 创建空白的表格
     * @return
     */
    public PdfPTable createBlankTable() {
        PdfPTable table = new PdfPTable(1);
        table.getDefaultCell().setBorder(0);
        table.addCell(createCell("", keyfont));
        table.setSpacingAfter(20.0f);
        table.setSpacingBefore(20.0f);
        return table;
    }
/**--------------------------创建表格的方法end------------------- ---------*/


}